package com.wjk.realm;

import com.wjk.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: RobertWei
 * time: 2021/8/14    10:44
 * @TODO:
 */

public class DbRealm extends AuthorizingRealm {
    /**
     * 授权会被调用 检查权限检查角色会被调用
     * 只要你根据账号信息, 返回用户有的权限和角色即可
     *
     * 注意:获取授权信息的方法, 当调用授权方法会触发
     *      需要根据认证通过的账号, 查询它对应的权限和角色
     *
     *
     * @param principals  doGetAuthorizationInfo/doGetAuthorizationInfo/第一个参数
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        System.out.println("user = " + user);

        //权限和集合
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<String> roles = new ArrayList<>();
        roles.add("teacher");
        roles.add("admin");
        info.addRoles(roles);
        List<String> permissions = new ArrayList<>();
        permissions.add("class:*");
        permissions.add("admin:a,b");
        info.addStringPermissions(permissions);

        return info;


    }

    /**
     * 当调用认证方式login会被调用
     * 传进来的就是 usernameandpasswordtoken 用户输入的账号和密码给我们
     *
     * 让你根据账号或者密码查询正确的认证信息 AuthenticationInfo 正确的信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //1. 获取传入的账号

        String username = (String) token.getPrincipal();
        //2.根据账号查询正确的用户信息
        User user = null;
        if (username.equalsIgnoreCase("root")) {
            user = new User();
            user.setUsername("root");
            user.setPassword("4db0fb8306ac057801e0b25adecd6511");
            user.setNick("ergouzi");
        }

        if(user == null){
            //如果根据账号没有查询到,
            return null;
        }

        //3.封装返回的info

        String salt = "erdaye";

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(salt),"realm");


        /**
         * 注意: realm的方法只需要正确的密码即可, 如果账号不正确, 返回null即可!
         */


        return info;
    }
}
